﻿using Sever2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Client
{
    class Program
    {
        static string IP;
        //客户端套接字
        static Socket clientSocket;
        static byte[] bs = new byte[1024];
        static void Main(string[] args)
        {
            Init: Console.Write("请输入服务器IP：");
            IP = Console.ReadLine();
            while (true)
            {
                string i;
                Console.WriteLine("1)检测服务器打开的端口");
                Console.WriteLine("2)输入要连接的端口");
                i=Console.ReadLine();
                if (int.Parse(i) == 1)
                {
                    SeachPort();
                }
                else
                {
                    break;
                }
            }
            Console.Write("输入要连接的端口:");
            string sport = Console.ReadLine();
            //string IP = "192.168.6.128";
            IPAddress ip = IPAddress.Parse(IP);
            int port = int.Parse(sport);

            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint endPoint = new IPEndPoint(ip, port);
            Conn conn = new Conn();
            while (!conn.isUse)
            {
                try
                {
                   clientSocket.Connect(endPoint);
                    conn.Init(clientSocket);
                }
                catch
                {
                    Console.WriteLine("连接"+ endPoint .ToString()+"失败");
                }
                Thread.Sleep(1000);
            }
            Console.WriteLine("连接" + endPoint.ToString() + "成功");
            conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, recieve, conn);
            while (true)
            {
                //连接服务器
                try
                {
                    while (clientSocket.Connected)
                    {
                        //发送字节
                        string str = Console.ReadLine();
                        if(str == "")
                        {
                            continue;
                        }
                        if (str == "断开")
                        {
                            clientSocket.Disconnect(false);
                            Thread.Sleep(1000);
                            goto Init;
                        }
                        byte[] message = Encoding.UTF8.GetBytes(str);
                        clientSocket.Send(message);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //clientSocket.Close();
            //Console.ReadKey();

        }
        static private void recieve(IAsyncResult asyncResult)
        {
            //获取接收对象
            Conn conn = (Conn)asyncResult.AsyncState;
            try
            {
                int count = conn.socket.EndReceive(asyncResult);
                //关闭信号
                if (count <= 0)
                {
                    Console.WriteLine("收到 [" + conn.GetAddress() + "] 断开连接");
                    conn.Close();
                    return;
                }
                
                //数据处理
                string str =  Encoding.UTF8.GetString(conn.readBuff, 0, count);
                if (Encoding.UTF8.GetString(conn.readBuff, 0, count) == "你活着吗")
                {
                    conn.socket.Send(Encoding.UTF8.GetBytes("我活着"));
                    conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, recieve, conn);
                    return;
                }
                Console.WriteLine("[" + conn.GetAddress() + "] : " + str);

                //继续接收
                conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, recieve, conn);

            }
            catch (Exception ex)
            {
                Console.WriteLine("[" + conn.GetAddress() + "] 断开连接");
                conn.Close();
            }
        }
        static private void SeachPort()
        {
           for(int i = 1; i < 6024; i++)
            {
                IPAddress ip = IPAddress.Parse(IP);
                int port = i;
                IPEndPoint endPoint = new IPEndPoint(ip, port);
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.BeginConnect(endPoint, ConnectCallBack, clientSocket);
            }
        }

        static private void ConnectCallBack(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            if (socket.Connected)
            {
                Console.WriteLine(socket.RemoteEndPoint);
                socket.Close();
            }
        }
    }
}
